using System;
using System.Windows.Input;
using Bookvar.ObjectModel.Actions;
using Bookvar.UI.Commands;

namespace Bookvar.UI.ViewModel
{
    public partial class HyperlinkWindowViewModel
    {
        private class SaveHyperlinkCommand : CommandModel
        {
            private readonly HyperlinkWindowViewModel viewModel;

            public SaveHyperlinkCommand( HyperlinkWindowViewModel viewModel )
                : base( BookvarCommands.SaveHyperlink )
            {
                this.viewModel = viewModel;
            }

            protected internal override void OnExecute( object sender, ExecutedRoutedEventArgs e )
            {
                Uri hyperlink;
                if ( TryCreateUri( e.Parameter, out hyperlink ) )
                {
                    var action = new ChangeTopicAction( viewModel.Topic ) { Hyperlink = hyperlink };
                    ActionService.Execute( action );
                }
            }

            protected internal override void OnCanExecute( object sender, CanExecuteRoutedEventArgs e )
            {
                Uri dummy;
                e.CanExecute = TryCreateUri( e.Parameter, out dummy );
                e.Handled = true;
            }

            private static bool TryCreateUri( object parameter, out Uri uri )
            {
                uri = parameter as Uri;
                if ( uri == null )
                {
                    string uriString = parameter as string;
                    if ( !string.IsNullOrEmpty( uriString ) )
                    {
                        return Uri.TryCreate( uriString, UriKind.RelativeOrAbsolute, out uri );
                    }
                    return false;
                }
                return true;
            }
        }
    }
}